﻿#include "scanruledao.h"
#include <QSqlError>
#include <QDebug>

ScanRuleDao::ScanRuleDao(QSqlDatabase sqlDatabase)
{
    db = sqlDatabase;
}

ScanRuleDao::~ScanRuleDao()
{

}

bool ScanRuleDao::getList(QList<ScanRule> &list)
{
    bool res = false;
    ScanRule scanRuleTmp;
    QSqlQuery sql_query(db);
    QString sqlStr = QString("%1").arg(scanRuleTmp.generateSelectSql());
    sql_query.prepare(sqlStr);
    if (sql_query.exec())
    {
        res = true;
        while (sql_query.next())
        {
            scanRuleTmp.clear();
            scanRuleTmp.fromSqlQuery(sql_query);
            list.append(scanRuleTmp);
        }
    }
    else
    {
        qCritical() << __FUNCTION__ << sql_query.lastError() << sqlStr;
    }
    return res;
}

bool ScanRuleDao::getOne(ScanRule &object)
{
    bool res = false;
    QSqlQuery sql_query(db);
    QString sqlStr = object.generateSelectSql();
    if (sql_query.exec(sqlStr))
    {
        res = true;
        if(sql_query.next()){
            object.fromSqlQuery(sql_query);
        }
    }
    else
    {
        qCritical() << __FUNCTION__ << sql_query.lastError() << sqlStr;
    }
    return res;
}

bool ScanRuleDao::saveOne(ScanRule &object)
{
    bool res = false;
    QSqlQuery sql_query(db);
    QString sqlStr = object.generateInsertSql();
    if(object.getId() != 0){
        sqlStr = object.generateUpdateSql(QBaseEntity::AllProperty);
    }
    if (sql_query.exec(sqlStr))
    {
        res = true;
    }
    else
    {
        qCritical() << __FUNCTION__ << sql_query.lastError() << sqlStr;
    }
    return res;
}

bool ScanRuleDao::deleteOne(ScanRule &object)
{
    bool res = false;
    QSqlQuery sql_query(db);
    QString sqlStr = object.generateDeleteSql();
    if (sql_query.exec(sqlStr))
    {
        res = true;
    }
    else
    {
        qCritical() << __FUNCTION__ << sql_query.lastError() << sqlStr;
    }
    return res;
}
